Introduction to Python/ko

소개

이것은 파이썬을 처음 접하는 사람들을 위한 짧은 자습서입니다. 파이썬은 오픈 소스, 다중 플랫폼프로그래밍 언어입니다.

다음은 매우 기본적인 소개일 뿐 완전한 자습서는 아닙니다. 그러나 이것이 FreeCAD와 그 메커니즘에 대한 추가 탐구를 위한 좋은 출발점이 되기를 바랍니다.파이썬 통역기에 아래 코드 조각을 입력하는 것이 좋습니다.

통역기

일반적으로 컴퓨터 프로그램을 작성할 때 텍스트 편집기나 특수 프로그래밍 환경(기본적으로 몇 가지 추가 도구가 포함된 텍스트 편집기)을 열고 프로그램을 작성한 다음 컴파일하고 실행합니다. 입력하는 동안 하나 이상의 오류가 발생하여 프로그램이 작동하지 않는 경우가 많습니다. 무엇이 잘못되었는지 알려주는 오류 메시지가 나타날 수도 있습니다. 그런 다음 텍스트 편집기로 돌아가 실수를 수정하고 다시 실행하며 프로그램이 의도한 대로 작동할 때까지 반복합니다.

파이썬에서는 이 모든 과정을 파이썬 인터프리터 내부에서 투명하게 처리할 수 있습니다. 인터프리터는 명령 프롬프트가 있는 파이썬 창으로, 여기에 파이썬 코드를 입력하기만 하면 됩니다. 컴퓨터에 파이썬이 설치되어 있다면(Windows 또는 Mac 사용자는 파이썬 웹사이트에서 다운로드하고, GNU/Linux 사용자는 패키지 저장소에서 설치하세요), 시작 메뉴에 파이썬 인터프리터가 표시됩니다. 하지만 앞서 언급했듯이 FreeCAD에도 내장 파이썬 인터프리터인 파이썬 콘솔이 있습니다.

The FreeCAD Python console

보이지 않으면 보기 → 패널 → Python 콘솔 을 클릭하세요. Python 콘솔은 크기를 조절할 수 있고 도킹 해제도 가능합니다.

인터프리터는 파이썬 버전을 표시한 다음 명령 프롬프트인 >>> 기호를 보여줍니다. 인터프리터에서 코드를 작성하는 것은 간단합니다. 한 줄이 하나의 명령입니다. Enter 키를 누르면 입력한 코드가 실행됩니다(컴파일 과정은 보이지 않지만 즉시 진행됩니다). 예를 들어 다음과 같이 작성해 보세요.

print("hello")

print() is a Python command that, obviously, prints something on the screen. When you press Enter, the operation is executed, and the message "hello" is printed. If you make an error, for example let's write:

print(hello)

파이썬은 즉시 오류를 알려줍니다. 이 경우 파이썬은 hello가 무엇인지 알지 못합니다. " " 문자는 내용이 문자열임을 나타냅니다. 프로그래밍 용어로 문자열은 텍스트를 의미합니다. 이 문자가 없으면 print() 명령은 hello를 인식하지 못합니다. 위쪽 화살표 키를 누르면 마지막 코드 줄로 돌아가서 수정할 수 있습니다.

파이썬 인터프리터에는 내장 도움말 시스템도 있습니다. 예를 들어 print(hello)에서 무엇이 잘못되었는지 이해하지 못했고 해당 명령에 대한 구체적인 정보를 얻고 싶다고 가정해 보겠습니다.

help(print)

print() 명령어가 할 수 있는 모든 것에 대한 길고 자세한 설명을 보게 될 것입니다.

이제 파이썬 인터프리터를 이해했으니, 좀 더 본격적인 내용으로 넘어가 보겠습니다.

Top

Variables

프로그래밍에서는 종종 값을 이름으로 저장해야 할 때가 있습니다. 이때 변수가 유용하게 사용됩니다. 예를 들어, 다음을 입력해 보세요.

a = "hello"
print(a)

You probably understand what happened here, we saved the string "hello" under the name a. Now that a is known we can use it anywhere, for example in the print() command. We can use any name we want, we just need to follow some simple rules, such as not using spaces or punctuation and not using Python keywords. For example, we can write:

hello = "my own version of hello"
print(hello)

이제 hello는 더 이상 정의되지 않은 변수가 아닙니다. 변수는 언제든지 수정할 수 있으며, 그 내용이 변경될 수 있다는 것이 변수의 이름입니다. 예를 들어:

myVariable = "hello"
print(myVariable)
myVariable = "good bye"
print(myVariable)

We changed the value of myVariable. We can also copy variables:

var1 = "hello"
var2 = var1
print(var2)

변수에는 의미 있는 이름을 붙이는 것이 좋습니다. 시간이 지나면 a라는 변수가 무엇을 나타내는지 기억하기 어려울 수 있습니다. 하지만 예를 들어 myWelcomeMessage와 같이 이름을 지으면 그 용도를 쉽게 기억할 수 있습니다. 또한 이렇게 하면 코드가 자체적으로 설명되는 데 한 걸음 더 가까워집니다.

대소문자를 구분하는 것이 매우 중요합니다. myVariablemyvariable은 서로 다릅니다. 만약 print(myvariable)을 입력하면 정의되지 않았다는 오류가 발생합니다.

Top

Numbers

물론 파이썬 프로그램은 텍스트 문자열뿐만 아니라 모든 종류의 데이터를 처리할 수 있습니다. 중요한 것은 파이썬이 어떤 종류의 데이터를 처리하는지 알아야 한다는 것입니다. 앞서 살펴본 `print hello` 예제에서 `print()` 명령어는 `hello` 문자열을 인식했습니다. `print()` 명령어를 사용하면 뒤따르는 내용이 텍스트 문자열임을 지정할 수 있습니다.

We can always check the data type of a variable with the type() command:

myVar = "hello"
type(myVar)

이를 통해 myVar의 내용이 'str'이며, 이는 문자열의 줄임말임을 알 수 있습니다. 또한 정수 및 부동 소수점 숫자와 같은 다른 기본 데이터 유형도 있습니다.

firstNumber = 10
secondNumber = 20
print(firstNumber + secondNumber)
type(firstNumber)

Python knows that 10 and 20 are integer numbers, so they are stored as 'int', and Python can do with them everything it can do with integers. Look at the results of this:

firstNumber = "10"
secondNumber = "20"
print(firstNumber + secondNumber)

여기서는 파이썬에게 두 변수가 숫자가 아니라 텍스트 조각이라고 인식하도록 했습니다. 파이썬은 두 텍스트를 더할 수 있지만, 물론 이 경우 산술 연산은 수행하지 않습니다. 하지만 우리는 정수에 대해 이야기하고 있었습니다. 부동 소수점 숫자도 있습니다. 차이점은 부동 소수점 숫자는 소수 부분이 있을 수 있지만 정수는 소수 부분이 없다는 것입니다.

var1 = 13
var2 = 15.65
print("var1 is of type ", type(var1))
print("var2 is of type ", type(var2))

정수와 실수는 문제없이 함께 사용할 수 있습니다.

total = var1 + var2
print(total)
print(type(total))

var2는 float형이기 때문에 Python은 결과값도 자동으로 float형이어야 한다고 판단합니다. 하지만 Python이 어떤 타입을 사용해야 할지 모르는 경우도 있습니다. 예를 들면 다음과 같습니다.

varA = "hello 123"
varB = 456
print(varA + varB)

This results in an error, varA is a string and varB is an integer, and Python doesn't know what to do. However, we can force Python to convert between types:

varA = "hello"
varB = 123
print(varA + str(varB))

Now that both variables are strings the operation works. Note that we "stringified" varB at the time of printing, but we didn't change varB itself. If we wanted to turn varB permanently into a string, we would need to do this:

varB = str(varB)

We can also use int() and float() to convert to integer and float if we want:

varA = "123"
print(int(varA))
print(float(varA))

You must have noticed that we have used the print() command in several ways. We printed variables, sums, several things separated by commas, and even the result of another Python command. Maybe you also saw that these two commands:

type(varA)
print(type(varA))

have the same result. This is because we are in the interpreter, and everything is automatically printed. When we write more complex programs that run outside the interpreter, they won't print automatically, so we'll need to use the print() command. With that in mind let's stop using it here. From now on we will simply write:

myVar = "hello friends"
myVar

Top

Lists

Another useful data type is a list. A list is a collection of other data. To define a list we use [ ]:

myList = [1, 2, 3]
type(myList)
myOtherList = ["Bart", "Frank", "Bob"]
myMixedList = ["hello", 345, 34.567]

As you can see a list can contain any type of data. You can do many things with a list. For example, count its items:

len(myOtherList)

Or retrieve one item:

myName = myOtherList[0]
myFriendsName = myOtherList[1]

While the len() command returns the total number of items in a list, the first item in a list is always at position 0, so in our myOtherList "Bob" will be at position 2. We can do much more with lists such as sorting items and removing or adding items.

Interestingly a text string is very similar to a list of characters in Python. Try doing this:

myvar = "hello"
len(myvar)
myvar[2]

Usually what you can do with lists can also be done with strings. In fact both lists and strings are sequences.

Apart from strings, integers, floats and lists, there are more built-in data types, such as dictionaries, and you can even create your own data types with classes.

Top

Indentation

One important use of lists is the ability to "browse" through them and do something with each item. For example look at this:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for dalton in alldaltons:
    print(dalton + " Dalton")

We iterated (programming jargon) through our list with the for in command and did something with each of the items. Note the special syntax: the for command terminates with : indicating the following will be a block of one of more commands. In the interpreter, immediately after you enter the command line ending with :, the command prompt will change to ... which means Python knows that there is more to come.

How will Python know how many of the next lines will need to be executed inside the for in operation? For that, Python relies on indentation. The next lines must begin with a blank space, or several blank spaces, or a tab, or several tabs. And as long as the indentation stays the same the lines will be considered part of the for in block. If you begin one line with 2 spaces and the next one with 4, there will be an error. When you have finished, just write another line without indentation, or press Enter to come back from the for in block

Indentation also aids in program readability. If you use large indentations (for example use tabs instead of spaces) when you write a big program, you'll have a clear view of what is executed inside what. We'll see that other commands use indented blocks of code as well.

The for in command can be used for many things that must be done more than once. It can, for example, be combined with the range() command:

serie = range(1, 11)
total = 0
print("sum")
for number in serie:
    print(number)
    total = total + number
print("----")
print(total)

If you have been running the code examples in an interpreter by copy-pasting, you will find the previous block of text will throw an error. Instead, copy to the end of the indented block, i.e. the end of the line total = total + number and then paste in the interpreter. In the interpreter press Enter until the three dot prompt disappears and the code runs. Then copy the final two lines followed by another Enter. The final answer should appear.

If you type into the interpreter help(range) you will see:

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

Here the square brackets denote an optional parameter. However all are expected to be integers. Below we will force the step parameter to be an integer using int():

number = 1000
for i in range(0, 180 * number, int(0.5 * number)):
    print(float(i) / number)

Another range() example:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for n in range(4):
    print(alldaltons[n], " is Dalton number ", n)

The range() command also has that strange particularity that it begins with 0 (if you don't specify the starting number) and that its last number will be one less than the ending number you specify. That is, of course, so it works well with other Python commands. For example:

alldaltons = ["Joe", "William", "Jack", "Averell"]
total = len(alldaltons)
for n in range(total):
    print(alldaltons[n])

Another interesting use of indented blocks is with the if command. This command executes a code block only if a certain condition is met, for example:

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Joe" in alldaltons:
    print("We found that Dalton!!!")

Of course this will always print the sentence, but try replacing the second line with:

if "Lucky" in alldaltons:

Then nothing is printed. We can also specify an else statement:

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Lucky" in alldaltons:
    print("We found that Dalton!!!")
else:
    print("Such Dalton doesn't exist!")

Top

Functions

There are very few standard Python commands and we already know several of them. But you can create your own commands. In fact, most of the additional modules that you can plug into your Python installation do just that, they add commands that you can use. A custom command in Python is called a function and is made like this:

def printsqm(myValue):
    print(str(myValue) + " square meters")

printsqm(45)

The def() command defines a new function, you give it a name, and inside the parenthesis you define the arguments that the function will use. Arguments are data that will be passed to the function. For example, look at the len() command. If you just write len(), Python will tell you it needs an argument. Which is obvious: you want to know the length of something. If you write len(myList) then myList is the argument that you pass to the len() function. And the len() function is defined in such a way that it knows what to do with this argument. We have done the same thing with our printsqm function.

The myValue name can be anything, and it will only be used inside the function. It is just a name you give to the argument so you can do something with it. By defining arguments you also to tell the function how many to expect. For example, if you do this:

printsqm(45, 34)

there will be an error. Our function was programmed to receive just one argument, but it received two, 45 and 34. Let's try another example:

def sum(val1, val2):
    total = val1 + val2
    return total

myTotal = sum(45, 34)

Here we made a function that receives two arguments, sums them, and returns that value. Returning something is very useful, because we can do something with the result, such as store it in the myTotal variable.

Top

Modules

Now that you have a good idea of how Python works, you will need to know one more thing: How to work with files and modules.

Until now, we have written Python instructions line by line in the interpreter. This method is obviously not suitable for larger programs. Normally the code for Python programs is stored in files with the .py extension. Which are just plain text files and any text editor (Linux gedit, emacs, vi or even Windows Notepad) can be used to create and edit them.

There are several of ways to execute a Python program. In Windows, simply right-click your file, open it with Python, and execute it. But you can also execute it from the Python interpreter itself. For this, the interpreter must know where your program is. In FreeCAD the easiest way is to place your program in a folder that FreeCAD's Python interpreter knows by default, such as FreeCAD's user Mod folder:

Let's add a subfolder there called scripts and then write a file like this:

def sum(a,b):
    return a + b

print("myTest.py succesfully loaded")

Save the file as myTest.py in the scripts folder, and in the interpreter window write:

import myTest

without the .py extension. This will execute the contents of the file, line by line, just as if we had written it in the interpreter. The sum function will be created, and the message will be printed. Files containing functions, like ours, are called modules.

When we write a sum() function in the interpreter, we execute it like this:

sum(14, 45)

But when we import a module containing a sum() function the syntax is a bit different:

myTest.sum(14, 45)

That is, the module is imported as a "container", and all its functions are inside that container. This is very useful, because we can import a lot of modules, and keep everything well organized. Basically when you see something.somethingElse, with a dot in between, then this means somethingElse is inside something.

We can also import our sum() function directly into the main interpreter space:

from myTest import *
sum(12, 54)

Almost all modules do that: they define functions, new data types and classes that you can use in the interpreter or in your own Python modules, because nothing prevents you from importing other modules inside your module!

How do we know what modules we have, what functions are inside and how to use them (that is, what kind of arguments they need)? We have already seen that Python has a help() function. Doing:

help("modules")

will give us a list of all available modules. We can import any of them and browse their content with the dir() command:

import math
dir(math)

We'll see all the functions contained in the math module, as well as strange stuff named __doc__, __file__, __name__. Every function in a well made module has a __doc__ that explains how to use it. For example, we see that there is a sin() function inside the math module. Want to know how to use it?

print(math.sin.__doc__)

It may not be evident, but on either side of doc are two underscore characters.

And finally one last tip: When working on new or existing code, it is better to not use the FreeCAD macro file extension, .FCMacro, but instead use the standard .py extension. This is because Python doesn't recognize the .FCMacro extension. If you use .py your code can be easily loaded with import, as we have already seen, and also reloaded with importlib.reload():

import importlib
importlib.reload(myTest)

There is however an alternative:

exec(open("C:/PathToMyMacro/myMacro.FCMacro").read())

Top

FreeCAD 시작

Hopefully you now have a good idea of how Python works, and you can start exploring what FreeCAD has to offer. FreeCAD's Python functions are all well organized in different modules. Some of them are already loaded (imported) when you start FreeCAD. Just try:

dir()

Top

Notes

Top